<?php
namespace App\Http\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Http\Constant;
use Illuminate\Support\Facades\DB;
use App\Http\Model\RbacRole;
use App\User;
use Illuminate\Hashing\BcryptHasher;
use Hash;
use Illuminate\Support\Facades\Crypt;

class RbacUser extends Model{
	protected $table = 'users';
	protected $primaryKey = 'id';

	public function createUser(Request $request, $init_password='123456'){
		$rbac_role_model = new RbacRole();
		$exist_role = $rbac_role_model->where('id', '=', $request->input('role_id'))
			->where('status', '=', Constant::TFEX_RBAC_ROLE_STATUS_OPEN)
			->get();
		if(0 == count($exist_role)){
			throw new \Exception('Rbac role [id='.$request->input('role_id').'] not exist.', Constant::EC_RBAC_ROLE_NOT_EXISTS);
		}else{
			$exist_user = $this->where('name', '=', $request->input('name'))
				->orWhere('email', '=', $request->input('email'))
				->get();
			if(0 != count($exist_user)){
				throw new \Exception('Rbac user [name='.$request->input('name').' or email='.$request->input('email').'] exist.', Constant::EC_RBAC_USER_EXISTS);
			}else{
				$this->role_id = $request->input('role_id');
				$this->name = $request->input('name');
				$this->email = $request->input('email');
				$this->password = $this->_createRbacUserPassword($init_password);
				$this->remember_token = $this->_createRbacUserRememberToken();
				$this->status = Constant::TFEX_USERS_STATUS_OPEN;
				$this->save();
				return $this->id;
			}
		}
	}

	public function updateStatus(Request $request, $user_status){
		//return $this->where('id', '=', $request->input('id'))->update(['status'=>$user_status]) !== false;
                return $this->where('id', '=', $request->input('id'))->delete() !== false;
	}

	public function _createRbacUserPassword($password){
		return app('hash')->make($password);
	}

	public function _createRbacUserRememberToken(){
		return str_random(10);
	}
}